<template>
  <el-dialog :title="dialogTitle" :visible.sync="showDialog_" top="0%" custom-class='dialog_right dialogScroll_add MkAddStaff' @open="openDialog" @close="closeDialog('addForm')">
    <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-200)+'px'}]">
      <el-form :model="addForm.formItem" :rules="addForm.rules" ref="addForm" label-width="110px" class="">
        <el-form-item label="员工工号" prop="number">
          <el-input v-model='addForm.formItem.number' placeholder="请输入员工工号（必填）" >
          </el-input>
        </el-form-item>
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model='addForm.formItem.name' placeholder="请输入员工姓名（必填）" >
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model='addForm.formItem.phone' placeholder="请输入员工手机号（必填）" :maxlength="11">
          </el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model='addForm.formItem.idCard' placeholder="请输入身份证号码" :maxlength="18">
          </el-input>
        </el-form-item>
        <el-form-item label="设置密码" prop="password" v-if="!currentCustomer">
          <el-input type="password" v-model='addForm.formItem.password' placeholder="请输入密码（必填）"  :maxlength="15">
          </el-input>
        </el-form-item>
        <el-form-item label="系统权限" prop="roleId">
          <el-select  placeholder="请选择系统权限（必选）" v-model='addForm.formItem.roleId'>
            <el-option v-for='item in roleData' :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" class="btn-primary" :disabled="clickSubmitBtn"
                 @click="submitForm('addForm')">保存</el-button>
      <el-button type="primary" class="btn-cancel" :disabled="clickSubmitBtn"
                 @click="showDialog_=false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import settingService from './../../../services/setting'
//  import * as constants from '../../../utils/constants'
  import {mapState} from 'vuex'
  export default {
    name: 'MkAddStaff',
    props: ['showDialog','currentCustomer'],
    computed:mapState({
      bodyHeight: state => state.global.bodyHeight,
    }),
    watch: {
      showDialog: function (value) {
        this.showDialog_ = value;
      }
    },
    methods: {
      changeField(form, formName, field) {
        this[form].formItem[field] = this[form].formItem[field].trim();
        this.$refs[formName].validateField(field);
      },
      openDialog() {
        this.isRefresh = 'no';
        this.clickSubmitBtn = false;
        this.loadRole();
        let currentCustomer = this.currentCustomer;
        let form  = this.addForm.formItem;
        if(currentCustomer) {
          this.dialogTitle = '编辑员工';
          form.phone = currentCustomer.phone;
          form.number = currentCustomer.number;
          form.idCard = currentCustomer.idCard;
          form.name = currentCustomer.name;
//          form.password = currentCustomer.password;
          form.roleId = currentCustomer.role.id;
          form.id = currentCustomer.id;
        }
//        console.log(form);
      },
      closeDialog(formName) {
        this.$refs[formName].resetFields();
        this.$emit('closeDialog',this.isRefresh);
      },
      submitForm(formName) {
        this.$refs[formName].validate(valid=>{
          if(valid) {
          	if(this.currentCustomer){
              if (!this.clickSubmitBtn) {
                this.fullscreenLoading = true;
                this.clickSubmitBtn = true;
                settingService.StaffEdit(this.addForm.formItem,data=>{
                  this.$message.success('保存成功');
                  this.isRefresh = 'yes';
                  this.showDialog_ = false;
                  this.fullscreenLoading = false;
                },data=>{
                  this.fullscreenLoading = false;
                  this.clickSubmitBtn = false;
                })
              }
            }
            else {
              if (!this.clickSubmitBtn) {
                this.fullscreenLoading = true;
                this.clickSubmitBtn = true;
                settingService.StaffAdd(this.addForm.formItem,data=>{
                  this.$message.success('保存成功');
                  this.isRefresh = 'yes';
                  this.showDialog_ = false;
                  this.fullscreenLoading = false;
                },data=>{
                  this.fullscreenLoading = false;
                  this.clickSubmitBtn = false;
                })
              }
            }
          }
        })
      },
      loadRole(){
        this.fullscreenLoading = true;
        settingService.StaffRole({fields:'id,name'}, (data) => {
          this.roleData = data.data;
//          console.log(this.roleData);
          this.fullscreenLoading = false;
        })
      }
    },
    data() {
    	let that=this;
      let checkPhone = (rule, value, callback) => {
        if (value) {
          let reg = new RegExp("^1(3|4|7|5|8)([0-9]{9})");
          if (!reg.test(value)) {
            callback(new Error('请输入正确格式的手机号'));
          } else {
            callback();
          }
        } else {
          callback(new Error('请输入联系电话'));
        }
      };
      let checkPassword = (rule, val, callback) => {
        var value=(val+'').trim();
        if (value == '') {
        	if(that.currentCustomer){
            callback();
          }
          else {
        		if(value.length<6){
              callback(new Error('请输入6-15位密码'));
            }
//            callback(new Error('密码不能为空'));
          }
        } else {
          var reg=/^[A-Za-z0-9]+$/g
          if (!reg.test(value)) {
            callback(new Error("密码只能由数字和字母组成"));
          }
          callback();
        }
      };
      let checkIdCard = (rule, val, callback) => {
        var value=(val+'').trim();
        if(value==''){callback()}
        else {
          var reg=/^[A-Za-z0-9]+$/g;
          if (!reg.test(value)) {
            callback(new Error('身份证号码只能由数字和字母组成'));
          }
          callback();
        }
      };
      let checkNumber= (rule, val, callback) => {
        var value=(val+'').trim();
        if (value == '') {
          callback(new Error('员工工号不能为空'));
        } else {
          var reg=/^[0-9]+$/g
          if (!reg.test(value)) {
            callback(new Error("员工工号只能由数字组成"));
          }
          callback();
        }
      };
      return {
//        timer: false,
        clickSubmitBtn: false,
        fullscreenLoading: false,
        titles:'',
        isRefresh: 'no',
        showDialog_: false,
        dialogTitle: '新增员工',
        addForm: {
          formItem: {
            id: '',
            phone: '',
            number: '',
            name: '',
            idCard: '',
            password: '',
            roleId:''
          },
          rules: {
            phone:{ validator: checkPhone, trigger: 'change' },
            name:{required:true,message:'请输入员工姓名',trigger:'change'},
//            password:{validator: checkPassword,trigger:'change'},
            password:{min: 6,message:'请输入6-15位的密码',trigger:'change'},
            idCard:{min: 18,validator: checkIdCard,trigger:'change'},
            number: {validator: checkNumber,trigger:'change'},
          }
        },
        roleData:[]
      }
    }
  }

</script>

<style lang="less">
  @import '../../../assets/style/main.less';
  .MkAddStaff {
  }
</style>
